#ifndef __SERIAL_PORT_HPP__
#define __SERIAL_PORT_HPP__

#include <string>
#include <termios.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
#include <thread>
#include <functional>
#include <queue>
#include <mutex>
#include <condition_variable>

namespace gimabl {

    enum class Parity {
        None,
        Even,
        Odd
    };
    enum class StopBits {
        One=1,
        Two
    };

    enum class FlowControl {
        None,
        Software,
        Hardware
    };
    enum class DataBits {
        Five=5,
        Six,
        Seven,
        Eight
    };


    class SerialPort {
        typedef std::function<int32_t(uint8_t*,std::size_t)> serialRecHandle;
    public:
        SerialPort(const std::string& port_name, int32_t baud_rate,DataBits bits=DataBits::Eight, Parity parity=Parity::None, 
            StopBits stop_bits=StopBits::One, FlowControl flow_control=FlowControl::None);
        ~SerialPort();

        int32_t openSerial();
        void closeSerial();

        bool isStopped() const;
        void startReceiving(serialRecHandle serialRecHandle,int32_t timeout_ms);
        
        void startWriteThread(int32_t timeout_ms);
        int32_t serialSend(const uint8_t *data, size_t len);

    private:
        void receiveLoop();
        void writeLoop();
        int32_t serialWrite(const void *data, size_t len);

        int32_t m_fd;
        std::string m_portName;
        int32_t m_baudRate;
        DataBits m_bits;
        Parity m_parity;
        StopBits m_stopBits;
        FlowControl m_flowControl;
        
        bool m_connected;
        bool m_stopped;
        serialRecHandle m_serialRecHandle;
        int32_t m_timeoutMs;
        std::thread m_recvThread;

        std::thread m_writeThread;
        std::queue<std::string> m_writeQueue;
        std::mutex m_writeMutex;
        std::condition_variable m_writeCv;  // 用于发送缓冲区的条件变量
        int32_t m_WtimeOutMs;
        bool m_startWriteThread;
    };
}


#endif // !1